<template>
	<view>
		<view class="venueForm">
			<view>
				<view style="font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;">请上传课程图片</view>
				<view style="color: #888888;font-size: 26rpx;line-height: 70rpx;">图片宽高建议750*339px</view>
			</view>
			<view>
				<u-upload name="img" :fileList="imgList"  @afterRead="onUpload($event, 'img')"
						@delete="onDelete($event, 'img')"  :maxCount="1"
					width="208rpx" height="208rpx">
				</u-upload>
			</view>
		</view>
		<view class="height30 bg-f1f1f1"></view>
		<view class="venueForm">
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>课程名称</view>
					<input class="fvalue" v-model="courseInfo.courseName"  placeholder="输入课程名称"  />
				</view>
			</view>
			<view class="height30"></view>
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>课程标签</view>
					<view class="fvalue" >
						<picker mode="selector" :range="courseTypeList" range-key="dictValue" @change="onCourseTypeChange">
							<view class="fvalue" >
								{{ courseInfo.courseTagsName || '选择课程标签' }}
							</view>
						</picker>
					</view>
				</view>
			</view>
			<view class="height30" v-if="courseInfo.courseType != 2"></view>
			<view v-if="courseInfo.courseType != 2">
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>归属场馆</view>
					<view class="fvalue" >
						<picker mode="selector" :range="venueList" range-key="venueName" @change="onVenueNameChange">
							<view class="fvalue" >
								{{ courseInfo.venueName || '选择课程归属场馆' }}
							</view>
						</picker>
					</view>
				</view>
			</view>
			<view class="height30"></view>
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>开课日期</view>
					<view class="fvalue" @click="effectiveDate.show = true" >{{ courseInfo.effectiveDate || '选择开课时间' }}</view>
				</view>
			</view>
			<view class="height30"></view>
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>开课时间</view>
					<view class="fvalue">
						<picker mode="time" :value="courseInfo.effectiveTime" @change="onChooseEffectiveTime">
							<view class="fvalue" >
								{{ courseInfo.effectiveTime || '请选择开课时间' }}
							</view>
						</picker>
					</view>
				</view>
			</view>
			<view class="height30"></view>
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>购买截止</view>
					<view class="fvalue" @click="lastBuyTime.show = true" >{{ courseInfo.lastBuyTime || '选择购买截止时间' }}</view>
				</view>
			</view>
			<view class="height30"></view>
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>开课人数</view>
					<input class="fvalue" type="number" v-model="courseInfo.minPeople"  placeholder="输入开课人数"  />
				</view>
			</view>
			<view class="height30"></view>
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>最大人数</view>
					<input class="fvalue" v-model="courseInfo.maxPeople" type="number"  placeholder="输入最大人数"  />
				</view>
			</view>
			<view class="height30"></view>
			<view>
				<view class="form-row">
					<view class="ftitle"><text class="required">*</text>购买费用</view>
					<input class="fvalue" v-model="courseInfo.purchaseCost" type="digit"  placeholder="输入购买费用"  />
				</view>
			</view>
		</view>
		<view class="height30 bg-f1f1f1"></view>
		<view class="venueForm">
			<view class="describe" style="font-size: 30rpx;line-height: 40rpx;">
				<view class="title" style="font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;">是否线上课程：</view>
				<view>课程是线上或者线下地址培训。</view>
			</view>
			<view style="padding-top: 20rpx;">
				<u-radio-group v-model="courseInfo.isOnline" placement="row" activeColor="#06ADAB">
					<u-radio size="35rpx" name="1" label="线上" labelSize="33rpx"></u-radio>
					<u-radio size="35rpx" name="0" label="线下" :customStyle="{marginLeft: '30rpx'}" labelSize="33rpx"></u-radio>
				</u-radio-group>
			</view>
			<view class="height30"></view>
			<view v-if="courseInfo.isOnline == '0'">
				<view class="form-row" style="padding: 25rpx 0rpx;">
					<view class="ftitle"><text class="required">*</text>线下地址</view>
					<view class="fvalue" style=" height: auto;   line-height: normal;" @click="selectChoose">{{ courseInfo.addrs || '选择课程位置' }}</view>
				</view>
			</view>
		</view>
		<view class="height30 bg-f1f1f1"></view>
		<view class="venueForm">
			<view class="textareaTitle"><text class="required">*</text>课程介绍</view>
			<view style="border: 1px solid #c3c3c3;">
				<textarea v-model="courseInfo.courseContent" style="width: 640rpx;padding: 20rpx;  height: 200rpx;font-size: 32rpx;" placeholder="请输入课程介绍"></textarea>
			</view>
		</view>
		
		<view class="height30 bg-f1f1f1"></view>
		<view class="venueForm">
			<view class="textareaTitle">注意事项</view>
			<view style="border: 1px solid #c3c3c3;">
				<textarea v-model="courseInfo.note" style="width: 640rpx;padding: 20rpx;  height: 200rpx;font-size: 32rpx;" placeholder="请输入注意事项"></textarea>
			</view>
		</view>
		
		<view style="padding-top: 30rpx;position: sticky;bottom: 0px;z-index: 10;background-color: #ffffff;">
			<view style="padding: 20rpx 40rpx;">
				<u-button text="保存课程" @click="submitNenueLocationApply" color="#155CCF"></u-button>
			</view>
		</view>
		
		
		<!-- 有效日期 -->
		<u-datetime-picker
				:show="effectiveDate.show"
				v-model="effectiveDate.value"
				mode="date"
				@confirm="effectiveDateConfirm"
				@cancel = "effectiveDate.show = false"
		></u-datetime-picker>
		
		<!-- 购买截止 -->
		<u-datetime-picker
				:show="lastBuyTime.show"
				v-model="lastBuyTime.value"
				mode="datetime"
				@confirm="lastBuyTimeConfirm"
				@cancel = "lastBuyTime.show = false"
		></u-datetime-picker>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//课程ID，用来辨别是否编辑
				courseId: '',
				//课程类型
				courseTypeList: [],
				//课程首页图片
				imgList: [],
				//提交表单
				courseInfo: {
					//课程类型(1:教练发布 2:场馆发布)
					courseType: '',
					//课程名称
					courseName: '',
					//课程图片
					img: '',
					//是否线上（0:线下，1：线上）
					isOnline: '1',
					//课程标签
					courseTags: '',
					//课程标签名称
					courseTagsName: '',
					//场馆ID
					venueId: '',
					//场馆名称
					venueName: '',
					//有效日期-开课日期
					effectiveDate: '',
					//开课时间
					effectiveTime: '',
					//最后购买时间-截止时间
					lastBuyTime: '',
					//最小人数（开课人数）
					minPeople: '',
					//最大人数
					maxPeople: '',
					//购买费用
					purchaseCost: '',
					//地址
					addrs: '',
					//经度
					lng: '',
					//纬度
					lat: '',
					//课程内容（课程简介）
					courseContent: '',
					//注意事项
					note: ''
				},
				//开课时间
				effectiveDate:{
					show: false,
					value: '',
				},
				//购买截止时间
				lastBuyTime:{
					show: false,
					value: '',
				},
				//当前登陆人拥有的场馆权限（教练员和指导员才有数据）
				venueList: [],
				//身份（1：普通用户，2：场馆主，3：教练员，4：指导员，5：体检中心）
				identity: ''
			}
		},
		onLoad(option) {
			//课程ID
			var courseId = option.courseId;
			this.courseId = courseId;
			//身份校验处理
			//identity身份（1：普通用户，2：场馆主，3：教练员，4：指导员，5：体检中心）
			//courseType课程类型(1:教练发布 2:场馆发布 3:指导员发布)
			var identity = uni.getStorageSync('identity');
			this.identity = identity;
			if( identity == 2 ){
				//场馆主
				this.courseInfo.courseType = 2;
				this.courseInfo.venueId = uni.getStorageSync('venueId');
			} else if(identity == 3) {
				//教练员，courseType=1
				this.courseInfo.courseType = 1;
				this.courseInfo.coachId = uni.getStorageSync('coachInstructorId');
				
			} else if(identity == 4) {
				//教练员，courseType=3
				this.courseInfo.courseType = 3;
				this.courseInfo.coachId = uni.getStorageSync('coachInstructorId');
			}
			this.initData();
			//选择的经纬度地址回执
			uni.$on("callLocationAddr",(data) => {
				this.courseInfo.addrs = data.address;
				this.courseInfo.lat = data.latitude;
				this.courseInfo.lng = data.longitude;
			});
		},
		onUnload(){
			uni.$off("callLocationAddr");
		},
		methods: {
			//当前登录人拥有的场馆权限
			venueData(){
				return new Promise((resolve, reject) => {
					//教练员和指导员才有权限处理
					if(this.identity == 3 || this.identity == 4 ) {
						//从缓存中获取授权的场馆数据
						var myVenueList = uni.getStorageSync('myVenueList');
						if(myVenueList){
							var venueList = JSON.parse(uni.getStorageSync('myVenueList'));
							
							//编辑将场馆ID转换场馆名称
							if(this.courseInfo.venueId){
								
								var venueObject = venueList.find(item => {
									return this.courseInfo.venueId == item.id;
								});
								if(venueObject){
									this.courseInfo.venueName = venueObject.venueName;
								}
							}
							
							this.venueList = venueList;
						} else {
							this.venueList = [];
						}
					}
					resolve([]);
				})
			},
			//初始化加载
			async initData(){
				if(this.courseId ){
					await this.courseDetail();
				}
				await this.courseTypeDict();
				await this.venueData();
			},
			//课程详情
			courseDetail(){
				return new Promise((resolve, reject) => {
					this.$request({
						url: '/blade-merchant-app/merchant-app/course/detail',
						type: 'GET',
						data: {'coursesId': this.courseId}
					}).then(res => {
						uni.hideLoading();
						var courseData = res.data;
						this.courseInfo = {
							//课程类型(1:教练发布 2:场馆发布)
							courseType: courseData.courseType,
							//课程名称
							courseName: courseData.courseName,
							//课程图片
							img: courseData.img,
							//是否线上（0:线下，1：线上）
							isOnline: courseData.isOnline.toString(),
							//课程标签
							courseTags: courseData.courseTags,
							//课程标签名称
							courseTagsName: '',
							//场馆ID
							venueId: courseData.venueId,
							//场馆名称
							venueName: '',
							//有效日期-开课日期
							effectiveDate: courseData.effectiveDate,
							//开课时间
							effectiveTime: courseData.effectiveTime,
							//最后购买时间-截止时间
							lastBuyTime: courseData.lastBuyTime,
							//最小人数（开课人数）
							minPeople: courseData.minPeople,
							//最大人数
							maxPeople: courseData.maxPeople,
							//购买费用
							purchaseCost: courseData.purchaseCost,
							//地址
							addrs: courseData.addrs,
							//经度
							lng: courseData.lng,
							//纬度
							lat: courseData.lat,
							//课程内容（课程简介）
							courseContent: courseData.courseContent,
							//注意事项
							note: courseData.note
						};
						this.imgList.push({ url: courseData.img });
						resolve(courseData); 
					}).catch(err =>{
						reject(err); 
					})
				})
			},
			//课程类型字典
			courseTypeDict(){
				return new Promise((resolve, reject) => {
					this.$request({
						url: '/blade-client-business/app/dict/getDictList',
						type: 'GET',
						data: {'code': 'knowledge_course_type'}
					}).then(res => {
						this.courseTypeList = res.data;
						if(this.courseInfo.courseTags){
							var courseTagsObject = res.data.find(item => {
								return this.courseInfo.courseTags == item.dictKey;
							});
							if(courseTagsObject){
								this.courseInfo.courseTagsName = courseTagsObject.dictValue;
							}
						}
						resolve(res.data); // 操作成功，处理结果
					}).catch(err =>{
						reject(err); 
					})
				});
			},
			// 开课时间确认
			effectiveDateConfirm(e) {
				const timeFormat = uni.$u.timeFormat;
				var effectiveDate = timeFormat(e.value, 'yyyy-mm-dd');
				this.courseInfo.effectiveDate = effectiveDate;
				this.effectiveDate.show = false;
			},
			// 购买截止确认
			lastBuyTimeConfirm(e) {
				const timeFormat = uni.$u.timeFormat;
				var lastBuyTime = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss');
				this.courseInfo.lastBuyTime = lastBuyTime;
				this.lastBuyTime.show = false;
			},
			//课程便签改变事件
			onCourseTypeChange(event) {
				const selectedIndex = event.detail.value; // 获取用户选择的选项索引
				const selectedOption = this.courseTypeList[selectedIndex]; // 获取用户选择的选项信息
				this.courseInfo.courseTagsName = selectedOption.dictValue;
				this.courseInfo.courseTags = selectedOption.dictKey;
			},
			//归属场馆改变事件
			onVenueNameChange(event) {
				const selectedIndex = event.detail.value; // 获取用户选择的选项索引
				const selectedOption = this.venueList[selectedIndex]; // 获取用户选择的选项信息
				this.courseInfo.venueId = selectedOption.id;
				this.courseInfo.venueName = selectedOption.venueName;
			},
			//开课时间
			onChooseEffectiveTime(e){
				this.courseInfo.effectiveTime = e.detail.value+':00';
			},
			//下一步保存按钮事件
			submitNenueLocationApply(){
				if(this.imgList.length<=0){
					uni.$u.toast("请上传课程图片")
					return ;
				}
				if(!this.courseInfo.courseName){
					uni.$u.toast("请输入课程名称")
					return ;
				}
				if(!this.courseInfo.courseTags){
					uni.$u.toast("请选择课程标签")
					return ;
				}
				if(this.identity == '3' || this.identity == '4'){
					if(!this.courseInfo.venueId){
						uni.$u.toast("请选择课程归属场馆")
						return ;
					}
				}
				if(!this.courseInfo.effectiveDate){
					uni.$u.toast("请选择开课时间")
					return ;
				}
				if(!this.courseInfo.lastBuyTime){
					uni.$u.toast("请选择购买截止时间")
					return ;
				}
				if(!this.courseInfo.minPeople){
					uni.$u.toast("请输入开课人数")
					return ;
				}
				if(!this.courseInfo.maxPeople){
					uni.$u.toast("请输入最大人数")
					return ;
				}
				if(!this.courseInfo.purchaseCost){
					uni.$u.toast("请输入购买费用")
					return ;
				}
				if(this.courseInfo.isOnline == '0' && (!this.courseInfo.addrs)){
					uni.$u.toast("请选择线下授课地址")
					return ;
				}
				
				if(!this.courseInfo.courseContent){
					uni.$u.toast("请输入课程介绍")
					return ;
				}
				let that=this
				uni.showModal({
					title: '提示',
					content: '确认保存课程?',
					success: function(res) {
						if (res.confirm) {
							that.saveOrUpdate();
						}
					}
				});
			},
			//提交保存
			saveOrUpdate(){
				const params = {
					...this.courseInfo
				};
				
				params.img = this.imgList.map(item => item.url).join(',');
				
				uni.showLoading({
					title: '保存中',
					mask: true
				})
				var saveUrl = '/blade-merchant-app/merchant-app/course/save';
				if(this.courseId){
					saveUrl = '/blade-merchant-app/merchant-app/course/update';
					params.id =  this.courseId;
				}
				
				
				this.$request({
					url: saveUrl,
					type: 'POST',
					data: params
				}).then(res => {
					uni.hideLoading();
					if(res.code == 200){
						uni.showModal({
						   title: '保存成功',
						   content: '可以在课程管理对新增课程进行管理',
						   showCancel: false,
						   success: function (res) {
							   if (res.confirm) {
								    uni.navigateBack()
							   }
						   }
						});
					} else {
						uni.showModal({
						   title: '新增失败',
						   content: res.msg,
						   showCancel: false,
						   success: function (res) {}
						});
					}
				}).catch(err =>{
					
				})
			},
			// 上传文件
			onUpload(files, type) {
				const {
					file
				} = files;
				let index = this[`${type}List`].length;
				this[`${type}List`].push({
					...file,
					status: 'uploading',
					message: '上传中'
				})
				this.$utils.onUploadFile(file.url)
					.then(res => {
						let item = this[`${type}List`][index];
						this[`${type}List`].splice(index, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: res.data.link
						}))
					})
			},
			// 删除图片
			onDelete(e, type) {
				this[`${type}List`].splice(e.index, 1);
			},
			//选择地址获取经纬度
			selectChoose() {
				var url = '/pagesWorkbenches/pages/amap-choose';
				uni.navigateTo({
					url: url
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f1f1f1;
		
		.bg-f1f1f1 {
			background: #f1f1f1;
		}
		
		.height30 {
			height: 30rpx;
		}
		
		.venueForm {
			padding: 40rpx;
			background-color: #ffffff;
			
			.textareaTitle {
				padding-bottom: 20rpx;font-size: 33rpx;color: #444444;font-weight: 600;line-height: 45rpx;
				
				.required {
					color: red;
				}
			}
			
			.form-row {
				border-radius: 0rpx;display: flex;border: 1px solid #c3c3c3;justify-content: center;align-items: center; 
				
				.ftitle {
					text-align: center;
					font-size: 30rpx;
					width: 180rpx;
					display: inline-table;
					color: #333333;
					padding:0rpx 10rpx;
					
					.required {
						color: red;
					}
				}
				.fvalue {
					height: 90rpx;width: 100%;font-size: 32rpx;line-height: 90rpx;
				}
			
			}
			
			
			.submitBtn {
				height: 90rpx;background-color: #0544ab;color: #ffffff;line-height: 90rpx;font-size: 32rpx;
			}
			
		}
		
	}

</style>
